//
//  WorkloadStatisticsViewController.m
//  EMMApp
//
//  Created by Mac on 16/6/15.
//  Copyright © 2016年 YiXun. All rights reserved.
//

#import "WorkloadStatisticsViewController.h"
#import "EMMAnalysisCell.h"
#import "KWFormView.h"
#import "GetWorkloadStatisticsListApi.h"

@interface WorkloadStatisticsViewController ()<UITableViewDelegate,UITableViewDataSource,KWFormViewDataSource,KWFormViewDelegate> {
    NSString *numString;
    NSInteger cHigth;
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *datas;
@property (nonatomic, strong) NSArray *titles;
@property (nonatomic, strong) NSArray *zjArr;

@property (strong, nonatomic) UIView *timerView;
@property (strong, nonatomic) UIButton *timerBtn;
@property (strong, nonatomic) KWFormView *formView;
@end

@implementation WorkloadStatisticsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatNavigationController];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, EMM_HEIGHT-SafeAreaTopHeight) style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_tableView];
    [self creatTimerShowUI];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 导航

- (void)creatNavigationController {
    [self updateNavBar];
    self.navigationItem.title = @"工作量统计";
    [self configLeftBtn];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    _datas = [[NSMutableArray alloc] init];
    [self postGetWorkloadStatisticsListApiWorkloadTimeType:@"1"];
}


- (void)postGetWorkloadStatisticsListApiWorkloadTimeType:(NSString *)workloadTimeType {
    [self showHudInWindow:@"正在加载请稍等..."];

    [_datas removeAllObjects];
    GetWorkloadStatisticsListApi *api = [[GetWorkloadStatisticsListApi alloc] initWithWorkloadTimeType:workloadTimeType];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetWorkloadStatisticsListApi *result = (GetWorkloadStatisticsListApi *)request;
        if (result.isSuccess) {
            GetWorkloadStatisticsList *get = result.resultData;
            NSMutableArray *arr2 = [[NSMutableArray alloc] init];
            NSMutableArray *arr3 = [[NSMutableArray alloc] init];
            NSMutableArray *arr4 = [[NSMutableArray alloc] init];
            NSMutableArray *arr5 = [[NSMutableArray alloc] init];
            NSMutableArray *arr6 = [[NSMutableArray alloc] init];
            for (WorkloadStatisticsList *list in get.workloadStatisticsList) {
                [_datas addObject:list];
                [arr2 addObject:list.followNum];
                [arr3 addObject:list.addCustomerNum];
                [arr4 addObject:list.payDepositNum];
                [arr5 addObject:list.subscribeNum];
                [arr6 addObject:list.signedNum];
            }
            cHigth = _datas.count*20 +40;
            
            NSString *str2;
            float num2 = 0;
            for (int i = 0; i < arr2.count; i++) {
                NSString *num = [arr2 objectAtIndex:i];
                num2 = num2 + [num floatValue];
                
            }
//            str2 = [NSString stringWithFormat:@"%f",num2];
            str2 = [NSString getVal:2 val:num2];
            NSString *str3;
            float num3 = 0;
            for (int i = 0; i < arr3.count; i++) {
                NSString *num = [arr3 objectAtIndex:i];
                num3 = num3 + [num floatValue];
                
            }
//            str3 = [NSString stringWithFormat:@"%.2f",num3];
            str3 = [NSString getVal:2 val:num3];

            NSString *str4;
            float num4 = 0;
            for (int i = 0; i < arr4.count; i++) {
                NSString *num = [arr4 objectAtIndex:i];
                num4 = num4 + [num floatValue];
                
            }
//            str4 = [NSString stringWithFormat:@"%.2f",num4];
            str4 = [NSString getVal:2 val:num4];

            NSString *str5;
            float num5 = 0;
            for (int i = 0; i < arr5.count; i++) {
                NSString *num = [arr5 objectAtIndex:i];
                num5 = num5 + [num floatValue];
                
            }
//            str5 = [NSString stringWithFormat:@"%.2f",num5];
            str5 = [NSString getVal:2 val:num5];


            NSString *str6;
            float num6 = 0;
            for (int i = 0; i < arr6.count; i++) {
                NSString *num = [arr6 objectAtIndex:i];
                num6 = num6 + [num floatValue];
                
            }
//            str6 = [NSString stringWithFormat:@"%.2f",num6];
            str6 = [NSString getVal:2 val:num6];

            self.zjArr = @[@"总计",str2,str3,str4,str5,str6];
            
        } else {
            [self showToast:result.resultData.errorMsg];
            /*
             提示语：账号权限发生变动，请重新登录
             code随机18位唯一码：108E65843mYuwqb01X
             //YUplf0wyU5vPVssLSG 对应的异地登录退出登录
             */
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"] || [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
        [_tableView reloadData];
        [self hideHud];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}


#pragma mark - UITableView代理
//返回几个表头
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

//每一个表头下返回几行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return cHigth+60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"EMMAnalysisCellId";
    EMMAnalysisCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"EMMAnalysisCell" owner:self options:nil] lastObject];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [cell addSubview:self.timerView];
    [self creat];
    [cell addSubview:_formView];
    
    return cell;
}

- (void)creatTimerShowUI {
    self.timerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, 40)];
    self.timerView.backgroundColor = [UIColor colorFromHexCode:@"#fff5e9"];
    
    _timerBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    _timerBtn.frame = CGRectMake(0, 0, EMM_WIDTH, 40);
    [_timerBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_timerBtn setTitle:@"今日" forState:UIControlStateNormal];
    [_timerBtn addTarget:self action:@selector(timerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    _timerBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.timerView addSubview:_timerBtn];
    
}

- (void)timerBtnClick:(UIButton *)btn {
    NSArray *arr = [NSArray arrayWithObjects:
                    @"今天",@"昨天",@"本周",
                    @"上周",@"本月",@"上月",@"近三月",@"今年", nil];
    ShowMenuView *menuView = [[ShowMenuView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) title:@"选项" titleNmae:@"选择时间" numLits:nil items:arr];
    menuView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    [[UIApplication sharedApplication].keyWindow addSubview:menuView];
    __block ShowMenuView *weakMenuView = menuView;//
    __block WorkloadStatisticsViewController *blockSelf = self;
    [menuView setTouchBlock:^(NSString *indet,NSString *number) {
        NSLog(@"%@",indet);
        if ([NSString isStringEmpty2:indet] == NO) {
            numString = indet;
            [_timerBtn setTitle:indet forState:UIControlStateNormal];
            [blockSelf postGetWorkloadStatisticsListApiWorkloadTimeType:number];
        }else {
            if ([NSString isStringEmpty2:numString] == NO) {
                [_timerBtn setTitle:numString forState:UIControlStateNormal];
            }else {
                [_timerBtn setTitle:@"今天" forState:UIControlStateNormal];
            }

        }
        [weakMenuView removeFromSuperview];
    }];
}

- (void)creat {
    self.titles = @[@"姓名",@"跟进",@"新增客户",@"认筹",@"认购",@"签约"];
 
    _formView = [[KWFormView alloc] initWithFrame:CGRectMake(10, 45, self.view.frame.size.width - 20, 0)];
    _formView.delegate = self;
    _formView.dataSource = self;
    
}

#pragma mark - formView dataSource
- (NSInteger)numberOfRowsInFormView:(KWFormView *)formView
{
    return self.datas.count + 2;
}

- (NSInteger)formViewColumnsInRow:(KWFormView *)formView
{
    return 6;
}

- (NSString *)formView:(KWFormView *)formView textForColumn:(NSInteger)column inRow:(NSInteger)row
{
    if (!row) {
        return self.titles[column];
    }if (row == self.datas.count+1) {
        return self.zjArr[column];
    } else {
        WorkloadStatisticsList *list = _datas[row - 1];
        if (column == 0) {
           return list.userName;
        }else if (column == 1) {
            return list.followNum;
        }else if (column == 2) {
            return list.addCustomerNum;
        }else if (column == 3) {
            return list.payDepositNum;
        }else if (column == 4) {
            return list.subscribeNum;
        }else {
            return list.signedNum;
        }
    }
}

- (UIColor *)formView:(KWFormView *)formView colorOfColumn:(NSInteger)column inRow:(NSInteger)row
{
    return [UIColor whiteColor];
}

- (UIColor *)formView:(KWFormView *)formView contentColorOfColumn:(NSInteger)column inRow:(NSInteger)row
{
    return [UIColor blackColor];
}

- (UIColor *)formViewBorderColor:(KWFormView *)formView
{
    return [UIColor blackColor];
}

- (CGFloat)formView:(KWFormView *)formView widthForColumn:(NSInteger)column
{
    return formView.bounds.size.width / 6.f;
}

- (CGFloat)formView:(KWFormView *)formView heightForRow:(NSInteger)row
{
    return 20;
}

- (BOOL)formView:(KWFormView *)formView addActionForColumn:(NSInteger)column inRow:(NSInteger)row
{
    return YES;
}

- (void)formView:(KWFormView *)formView didSelectColumn:(NSInteger)column inRow:(NSInteger)row
{
    NSLog(@"%@",[formView itemAtColumn:column inRow:row].currentTitle);
}


@end
